package com.teen9g.infoplatformserver.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.teen9g.PageQueryDTO.PlaygroundPageQueryDTO;
import com.teen9g.constant.CategoryConstant;
import com.teen9g.constant.PlaygroundConstant;
import com.teen9g.constant.RedisKey;
import com.teen9g.context.BaseContext;
import com.teen9g.dto.PlaygroundDTO;
import com.teen9g.entity.Playground;
import com.teen9g.entity.SingleRecentEdit;
import com.teen9g.infoplatformserver.mapper.PlaygroundMapper;
import com.teen9g.infoplatformserver.mapper.RecentEditMapper;
import com.teen9g.infoplatformserver.service.PlaygroundService;
import com.teen9g.userVO.PlaygroundUserVO;
import com.teen9g.utils.StringUtil;
import com.teen9g.vo.PlaygroundVO;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class PlaygroundServiceImpl implements PlaygroundService {

    @Autowired
    private PlaygroundMapper playgroundMapper;

    @Autowired
    private RecentEditMapper recentEditMapper;

    @Autowired
    private RedisTemplate<String, Long> redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public Playground getById(Integer id) {
        return playgroundMapper.selectById(id);
    }

    @Override
    public String add(PlaygroundDTO playgroundDTO) {
        Playground playground = Playground.builder()
                .contentCreateTime(LocalDateTime.now())
                .contentUpdateTime(LocalDateTime.now())
                .contentAuthor(BaseContext.getCurrentUser())
                .contentRecentEditor(BaseContext.getCurrentUser())
                .build();
        BeanUtils.copyProperties(playgroundDTO, playground);
        int insert = playgroundMapper.insert(playground);
        return insert > 0 ?
                PlaygroundConstant.ADD_SUCCESS : PlaygroundConstant.ADD_FAILED;
    }

    @Override
    public String update(PlaygroundDTO playgroundDTO, Integer id) throws JSONException {
        //判断传入的实体是否存在
        if (playgroundDTO == null) {
            return PlaygroundConstant.UPDATE_ERROR;
        }
        //判断id是否存在
        if (id == null) {
            return PlaygroundConstant.UPDATE_ID_ERROR;
        }
        //判断对应的实体是否存在
        Playground playground = playgroundMapper.selectById(id);
        if (playground == null) {
            return PlaygroundConstant.UPDATE_NOT_FOUND;
        }
        PlaygroundDTO temp = new PlaygroundDTO();
        BeanUtils.copyProperties(playground, temp);
        //先找出更新了什么内容
        StringUtil stringUtil = new StringUtil();
        String operation = stringUtil.PG_getOperation(playgroundDTO, temp);
        if (!operation.isEmpty()) {
            //先插入一条编辑记录
            SingleRecentEdit singleRecentEdit = SingleRecentEdit.builder()
                    .updateEditor(BaseContext.getCurrentUser())
                    .updateTime(LocalDateTime.now())
                    .contentCategory(CategoryConstant.PLAYGROUND)
                    .contentId(id)
                    .contentTitle(playgroundDTO.getContentTitle())
                    .updateOperation(operation)
                    .build();
            recentEditMapper.insert(singleRecentEdit);
        }
        //再更新内容
        BeanUtils.copyProperties(playgroundDTO, playground);
        playground.setContentUpdateTime(LocalDateTime.now());
        playground.setContentRecentEditor(BaseContext.getCurrentUser());
        int update = playgroundMapper.updateById(playground);
        return update > 0 ?
                PlaygroundConstant.UPDATE_SUCCESS : PlaygroundConstant.UPDATE_FAILED;
    }

    @Override
    public String delete(Integer id) {
        if (id == null) {
            return PlaygroundConstant.DELETE_ID_ERROR;
        }
        Playground playground = playgroundMapper.selectById(id);
        if (playground == null) {
            return PlaygroundConstant.DELETE_NOT_FOUND;
        }
        if (!Objects.equals(playground.getContentAuthor(), BaseContext.getCurrentUser())) {
            return PlaygroundConstant.DELETE_NOT_AUTHOR;
        }
        int delete = playgroundMapper.deleteById(id);
        return delete > 0 ?
                PlaygroundConstant.DELETE_SUCCESS : PlaygroundConstant.DELETE_FAILED;
    }

    @Override
    public PageInfo<PlaygroundVO> page(PlaygroundPageQueryDTO playgroundPageQueryDTO) {
        PageHelper.startPage(playgroundPageQueryDTO.getPageNum(),
                playgroundPageQueryDTO.getPageSize());
        List<PlaygroundVO> list = playgroundMapper.selectByPage(playgroundPageQueryDTO);
        return new PageInfo<>(list);
    }

    @Override
    public void addView(Integer id) {
        redisTemplate.opsForValue().increment(RedisKey.PL_VIEW_KEY + id);
    }

    @Override
    public PageInfo<PlaygroundUserVO> pageUser(PlaygroundPageQueryDTO playgroundPageQueryDTO) {
        PageHelper.startPage(playgroundPageQueryDTO.getPageNum(),
                playgroundPageQueryDTO.getPageSize());
        List<PlaygroundUserVO> list = playgroundMapper.selectByPageUser(playgroundPageQueryDTO);
        for (PlaygroundUserVO playgroundUserVO : list) {
            if (playgroundUserVO.getContentImage() != null) {
                //提取出图片的第一张用于展示
                try {
                    String[] images = objectMapper.readValue(playgroundUserVO.getContentImage(), String[].class);
                    if (images.length > 0) {
                        playgroundUserVO.setContentImage(images[0]);
                    }
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return new PageInfo<>(list);

    }
}
